package com.masonluo.mlonlinejudge.service.impl;

import com.masonluo.mlonlinejudge.dao.IndexProblemRepository;
import com.masonluo.mlonlinejudge.entity.IndexProblem;
import com.masonluo.mlonlinejudge.exceptions.ResourceNotFoundException;
import com.masonluo.mlonlinejudge.mapper.IndexProblemMapper;
import com.masonluo.mlonlinejudge.model.bo.IndexProblemBo;
import com.masonluo.mlonlinejudge.model.bo.ProblemBo;
import com.masonluo.mlonlinejudge.model.param.ProblemParam;
import com.masonluo.mlonlinejudge.service.IndexProblemService;
import com.masonluo.mlonlinejudge.service.IndexService;
import com.masonluo.mlonlinejudge.service.ProblemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author masonluo
 * @date 2021/2/10 3:48 下午
 */
@Service
public class IndexProblemServiceImpl implements IndexProblemService {
    @Autowired
    private IndexProblemRepository ipRespository;

    @Autowired
    private IndexService indexService;

    @Autowired
    private ProblemService problemService;

    @Override
    public IndexProblemBo relatedProblem(Integer indexId, List<Integer> problemIds) {
        if (!indexService.exist(indexId)) {
            throw new ResourceNotFoundException("The index [" + indexId + "] does not exist");
        }
        List<ProblemParam> problems = problemService.listByIds(problemIds);
        if (problems.size() != problemIds.size()) {
            throw new ResourceNotFoundException("The problem id does not exist in database");
        }
        List<IndexProblem> indexProblems = new ArrayList<>();
        for (Integer problemId : problemIds) {
            IndexProblem ip = new IndexProblem();
            ip.setProblemId(problemId);
            ip.setIndexId(indexId);
            indexProblems.add(ip);
        }
        ipRespository.insertAll(indexProblems);
        ArrayList<Integer> list = new ArrayList<>();
        IndexProblemBo bo = new IndexProblemBo();
        bo.setIndexId(indexId);
        bo.setProblemId(problemIds);
        return bo;
    }

    @Override
    public void deleteByIndexIdAndProblemId(Integer indexId, Integer problemId) {
        ipRespository.deleteByIndexIdAndProblemId(indexId, problemId);
    }

}
